import md5 from "md5.js";
import NetWork from './network'

// 正式环境
const isReleaseUrl = true
// 测试环境
// const isReleaseUrl = false

// 跳转找房版本
// "trial" 体验版   
const envVersion = "develop"
// "develop" 开发版
// const envVersion = "trial"

let domain;
let houseDomain;
let ImagesUrl;
let shareUrl;
let aistFilesvrWebUrl;

// 李相龙
let lxl_domain = 'http://192.168.66.41:8080/unified-user-gateway/api/v1/'
let lxl_houseDomain = "https://api.shulanfd.com/shulan-jjr-gateway/api/v1/"
const releaseImagesUrl = "https://api.shulanfd.com/aist-filesvr-web/api/files/"

//生产
if (isReleaseUrl) {
  domain = 'https://api.shulanfd.com/unified-user-gateway/api/v1/';
  houseDomain = 'https://api.shulanfd.com/shulan-jjr-gateway/api/v1/';
  ImagesUrl = releaseImagesUrl;
  shareUrl = "https://api.shulanfd.com/shulan-jjr-gateway/";
  aistFilesvrWebUrl = "https://api.shulanfd.com/aist-filesvr-web/api/";

  // 测试域名
  //江城本地地址 http://94fj5h.natappfree.cc
} else {  domain = 'https://api-dev.shulanfd.com/unified-user-gateway/api/v1/';
  houseDomain = 'https://api-dev.shulanfd.com/shulan-jjr-gateway/api/v1/';
  ImagesUrl = "https://api-dev.shulanfd.com/aist-filesvr-web/api/files/";
  shareUrl = "https://api-dev.shulanfd.com/shulan-jjr-gateway/";
  aistFilesvrWebUrl = "https://api-dev.shulanfd.com/aist-filesvr-web/api/";
}

// houseDomain = 'http://10.10.138.35:8080/shulan-jjr-gateway/api/v1/';

//时间转换
const formatDateTime = (timeStamp, params) => {
  var date = new Date(timeStamp);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  //day 有值-返回带分秒的
  if (params == '' || params == null || params == 'undefind') {
    return y + '/' + m + '/' + d
  } else {
    if(params===true){
      return y + '/' + m + '/' + d + ' ' + h + ':' + minute;
    } else {
      return y + '/' + m + '/' + d + ' ' + h + ':' + minute + ':' + second;
    }
  }
}

const dateFormat = (date, fmt) => {
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    'S': date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
  }
  return fmt;
}

//获取token
const getToken = (tokenString) => {
  var date = new Date();
  date = date.getTime();
  var sign = tokenString + date + (date % 34);
  sign = md5.hex_md5(sign);
  wx.setStorageSync("date", date);
  wx.setStorageSync("sign", sign);
  wx.setStorageSync("tokenString", tokenString);
  wx.setStorageSync("token", tokenString + date + sign);
  return tokenString + date + sign;
}

//token是否过期
const checkToken = () => {
  var date = wx.getStorageSync("date");
  var now = new Date();
  now = now.getTime();
  var differ = now - date;
  return differ / 1000 / 60 / 60;
}

// 限制请求重复
let urls = []
let loadingTimeHandler = null
let loadingStatus = false
const request = (url, data, method, success, fail, params = {}) => {
  return new Promise((resolve, reject) => {
    /**
     * customHeader 自定义头部
     * isAllowRepeat  是否允许重复的请求
     * isFilterNull 过滤值为null的字段
     * loading 接口慢时展示加载中...
     * maxTimeOut 超时时间 
     */
    const { customHeader, isAllowRepeat, isFilterNull, loading, maxTimeOut } = params;
    success = success || (()=>{})
    if (!NetWork.getInstance().isConnected) {
      wx.showToast({
        title: `网络已断开，检查网络后重试`,
        icon: "none",
        duration: 5000
      })
      return
    }

    if(isFilterNull) {
      data = filterNull(data)
      function filterNull(data) {
        if(isWhatType(data) === "Object") {
          const result = {};
          Object.keys(data).forEach(key => {
            if(!(data[key] === null)) {
              result[key] = data[key];
            }
          })
          return result;
        } else {
          return data
        }
        function isWhatType(o) {
          return Object.prototype.toString.call(o).slice(8, -1)
        }
      }
    }
    var token = checkToken() >= 1 ? getToken(wx.getStorageSync("tokenString")) : wx.getStorageSync("token");

    console.log("【请求<<<====】", url, data) 

    let _url = url;
    if (urls.indexOf(_url) > -1 && !isAllowRepeat) {
      console.warn("重复的请求", _url) 
      return
    }
    urls.push(_url)
    // 当传给后端的数值为null时直接拦截该参数
    if (data) {
      for (var key in data) {
        if (data[key] == null || typeof(data[key]) == "undefined") {
          delete data[key];
        }
      }
    }
    NetWork.getInstance().request()

    // 加载动画
    if (loading) {
      loadingTimeHandler && clearTimeout(loadingTimeHandler)
      loadingTimeHandler = setTimeout(() => {
        loadingStatus = true
        wx.showLoading({ title: '请求中...', })
      }, 200)
    }

    // 设置超时
    if (maxTimeOut) {
      success.timerClearHandler = setTimeout(() => {
        success.timeout = true
        fail && fail()
        if (loadingStatus) {
          loadingStatus = false
          wx.hideLoading()
        }
      }, maxTimeOut)
    }

    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        ...customHeader,
        Accept: "text/html, application/xhtml+xml, */*",
        token: token
      },
      success: function(res) {
        console.log("【success数据返回====>>】", url, res.data) 
        
        // 已超时
        if (success.timeout) return
        if (success.timerClearHandler) {
          clearTimeout(success.timerClearHandler)
        }
        resolve(res)
        success(res);
      },
      fail: function(res) {
        reject(res)
        console.log("【error数据返回====>>】", url, res) 

        if (success.timeout) return
        if (success.timerClearHandler) {
          clearTimeout(success.timerClearHandler)
        }

        //请求失败
        if (fail) {
          fail(res)
        } else {
          wx.showToast({
            title: '网络错误~',
            icon: "none",
            duration: 3000
          })
        }
      }, 
      complete() {
        urls = urls.filter((item) => {
          return item != _url
        })
        NetWork.getInstance().requestOver()
        if (loadingStatus) {
          loadingStatus = false
          wx.hideLoading()
        }
        if (loadingTimeHandler) {
          clearTimeout(loadingTimeHandler)
          loadingTimeHandler = null
        }
      }
    })
  })
}

const requestGet = (url, data, success, fail, params) => {
  return request(url, data, "GET", success, fail, params)
}
const requestPost = (url, data, success, fail, params) => {
  return request(url, data, "POST", success, fail, params)
}
const requestDelete = (url, data, success, fail, params) => {
  return request(url, data, "DELETE", success, fail, params)
}

const requestPut = (url, data, success, fail, params) => {
  return request(url, data, "PUT", success, fail, params)
}

//选择图片
const updateImages = (count, success, fail) => {
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        success(res);
      }
    })
  }
  //上传图片
const uploadFiles = (tempFilePaths, success) => {
    wx.uploadFile({
      url: ImagesUrl,
      filePath: tempFilePaths,
      name: "file",
      formData: {
        "filetype": "image"
      },
      name: 'file',
      success(res) {
        success(res);
      }
    })
  }
  //下载图片
const downloadFiles = (tempFilePaths, success) => {
  wx.downloadFile({
    url: ImagesUrl,
    filePath: tempFilePaths,
    name: "file",
    formData: {
      "filetype": "image"
    },
    name: 'file',
    success(res) {
      success(res);
    }
  })
}
module.exports = {
  isReleaseUrl,
  domain: domain,
  houseDomain: houseDomain,
  ImagesUrl: ImagesUrl,
  shareUrl: shareUrl,
  getToken: getToken,
  request: request,
  requestDelete,
  requestGet: requestGet,
  requestPost: requestPost,
  requestPut: requestPut,
  updateImages: updateImages,
  uploadFiles: uploadFiles,
  downloadFiles: downloadFiles,
  formatDateTime: formatDateTime,
  envVersion,
  lxl_domain,
  lxl_houseDomain,
  aistFilesvrWebUrl,
  dateFormat,
  releaseImagesUrl,
}